package controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import pojo.HospitalBed;
import service.HospitalBedService;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;

/**
 * 医院病床管理控制器
 */
@RestController
@RequestMapping(value = "/hospitalBed")
@CrossOrigin(origins = "*")
@Api(tags = "医院病床管理接口")
public class HospitalBedController {

    @Autowired
    private HospitalBedService hospitalBedService;

    // 基础上传目录（所有自定义目录的父目录）
    private static final String BASE_UPLOAD_DIR = "D:/uploads/";

    /**
     * 上传病床头像并指定保存目录
     */
    @PostMapping(value = "/uploadAvatar/{id}")
    @ApiOperation(value = "上传病床头像", notes = "上传病床头像并保存到指定目录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "病床ID", required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "directory", value = "保存目录（可选）", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "file", value = "头像文件", required = true, dataType = "__file", paramType = "form")
    })
    public String uploadAvatar(
            @PathVariable Integer id,
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "directory", defaultValue = "") String directory
    ) {
        try {
            if (file.isEmpty()) {
                return "上传失败：文件为空";
            }

            // 构建完整上传路径
            String uploadPath = buildUploadPath(directory);
            Path filePath = createFileInDirectory(uploadPath, file);

            // 更新病床信息中的头像路径
            HospitalBed bed = hospitalBedService.findHospitalBedById(id);
            if (bed != null) {
                // 存储相对路径（相对于基础目录）
                String relativePath = filePath.toString().substring(BASE_UPLOAD_DIR.length());
                bed.setTouxiang("/uploads/" + relativePath);
                hospitalBedService.updateHospitalBed(bed);
                return "success";
            } else {
                return "更新失败：病床不存在";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败：" + e.getMessage();
        }
    }

    /**
     * 获取所有病床列表
     */
    @GetMapping(value = "/list")
    @ApiOperation(value = "获取所有病床列表", notes = "返回系统中所有病床的信息")
    public List<HospitalBed> getHospitalBedList() {
        return hospitalBedService.findAllHospitalBeds();
    }

    /**
     * 获取单个病床详情
     */
    @GetMapping(value = "/detail/{id}")
    @ApiOperation(value = "获取单个病床详情", notes = "根据病床ID获取详细信息")
    @ApiImplicitParam(name = "id", value = "病床ID", required = true, dataType = "int", paramType = "path")
    public HospitalBed getHospitalBedDetail(@PathVariable("id") Integer id) {
        return hospitalBedService.findHospitalBedById(id);
    }

    /**
     * 添加病床
     */
    @PostMapping(value = "/create")
    @ApiOperation(value = "添加病床", notes = "创建新的病床信息")
    @ApiParam(name = "hospitalBed", value = "病床实体", required = true)
    public String create(@RequestBody HospitalBed hospitalBed) {
        hospitalBedService.saveHospitalBed(hospitalBed);
        return "success";
    }

    /**
     * 更新病床信息
     */
    @PostMapping(value = "/update")
    @ApiOperation(value = "更新病床信息", notes = "根据病床ID更新病床信息")
    @ApiParam(name = "hospitalBed", value = "病床实体，需包含ID", required = true)
    public String update(@RequestBody HospitalBed hospitalBed) {
        hospitalBedService.updateHospitalBed(hospitalBed);
        return "success";
    }

    /**
     * 删除病床
     */
    @PostMapping(value = "/del/{id}")
    @ApiOperation(value = "删除病床", notes = "根据病床ID删除对应病床")
    @ApiImplicitParam(name = "id", value = "病床ID", required = true, dataType = "int", paramType = "path")
    public String del(@PathVariable("id") Integer id) {
        hospitalBedService.deleteHospitalBed(id);
        return "success";
    }

    // 辅助方法：构建上传路径
    private String buildUploadPath(String directory) throws IOException {
        // 防止目录遍历攻击
        if (directory.contains("..") || directory.contains("/") || directory.contains("\\")) {
            throw new IllegalArgumentException("目录名包含非法字符");
        }

        // 如果目录为空，使用默认路径
        String uploadPath = directory.isEmpty()
                ? BASE_UPLOAD_DIR
                : BASE_UPLOAD_DIR + directory + "/";

        // 确保目录存在
        Path path = Paths.get(uploadPath);
        if (!Files.exists(path)) {
            Files.createDirectories(path);
        }

        return uploadPath;
    }

    // 辅助方法：在指定目录创建文件
    private Path createFileInDirectory(String uploadPath, MultipartFile file) throws IOException {
        String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
        Path filePath = Paths.get(uploadPath + fileName);
        file.transferTo(filePath.toFile());
        return filePath;
    }
}